package com.ajun.simple;

import com.ajun.common.ConnectionFactoryBuilder;
import com.ajun.common.QueueConstants;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * Simple 模式 - 消费者
 *
 * @author AJun
 * @date 2021-07-14
 */
@Slf4j
public class Consumer {

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            // 创建连接 Connection
            connection = ConnectionFactoryBuilder.getConnection("消费者");
            // 获取通道 Channel
            channel = connection.createChannel();
            // 通过 Channel 创建交换机、声明队列、绑定关系、设置路由键、接受消息
            channel.queueDeclare(QueueConstants.SIMPLE_QUEUE, false, false, false, null);
            // 接收消息
            channel.basicConsume(QueueConstants.SIMPLE_QUEUE, true,
                (consumerTag, message) ->
                    log.debug("消息接收成功, message => {}", new String(message.getBody(), StandardCharsets.UTF_8)),
                consumerTag ->
                    log.error("消息接收失败")
            );
            log.debug("接收消息...");
            System.in.read();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionFactoryBuilder.close(channel, connection);
        }
    }
}
